<script setup lang="ts">
defineOptions({
  name: "WorkAssignments"
});

import { ref, onMounted, reactive } from "vue";
import {
  ElButton,
  ElInput,
  ElTable,
  ElTableColumn,
  ElPagination,
  ElTag,
  ElMessage,
  ElMessageBox,
  ElDialog,
  ElForm,
  ElFormItem,
  ElDatePicker,
  ElLoading,
  ElCol,
  ElRow
} from "element-plus";
import {
  getWorkAssignmentList,
  getWorkAssignmentById,
  addWorkAssignment,
  updateWorkAssignment,
  deleteWorkAssignment,
  submitReceipt
} from "@/api/workAssignment";
import type {
  WorkAssignmentListVo,
  WorkAssignmentQueryDto,
  WorkAssignmentAddDto,
  WorkAssignmentUpdateDto,
  WorkAssignmentReceiptDto
} from "@/api/workAssignment";

// 搜索相关
const searchKeyword = ref("");
const selectedCompletionStatus = ref("");

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const totalCount = ref(0);
const loading = ref(false);
const workAssignments = ref<any[]>([]);

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref("新增派工信息");
const isEdit = ref(false);
const isDetail = ref(false);
const formRef = ref();

// 完成状态选项
const completionStatusOptions = [
  { label: "未完成", value: "未完成" },
  { label: "已完成", value: "已完成" },
  { label: "进行中", value: "进行中" }
];

// 处理情况选项
const handlingSituationOptions = [
  { label: "已完成", value: "已完成" },
  { label: "已完成并待收款", value: "已完成并待收款" },
  { label: "未完成", value: "未完成" }
];

// 回单弹窗相关
const receiptDialogVisible = ref(false);
const receiptFormRef = ref();
const currentRepair = ref<WorkAssignmentListVo | null>(null);
const receiptForm = reactive({
  repairReportId: 0,
  handlingSituation: "已完成", // 默认已完成
  remarks: ""
});

// 回单表单校验规则
const receiptRules: FormRules = {
  handlingSituation: [
    { required: true, message: "请选择处理情况", trigger: "change" }
  ]
};

// 表单数据
const formData = reactive({
  id: undefined,
  repairReportId: undefined,
  assignmentTime: "",
  handler: "",
  totalFee: 0,
  serviceAddress: "",
  requiredTasks: "",
  assignmentNotes: "",
  completionTime: "",
  completionStatus: "未完成"
});

// 导入Element Plus表单规则类型
import type { FormRules } from "element-plus";

// 表单校验规则
const rules: FormRules = {
  assignmentTime: [
    { required: true, message: "请选择派发时间", trigger: "change" }
  ],
  handler: [{ required: true, message: "请选择处理人", trigger: "change" }],
  totalFee: [
    { required: true, message: "请输入计费总额", trigger: "blur" },
    { type: "number", min: 0, message: "计费总额不能为负数", trigger: "blur" }
  ],
  serviceAddress: [
    { required: true, message: "请输入服务地址", trigger: "blur" }
  ],
  requiredTasks: [
    { required: true, message: "请输入要求处理事项", trigger: "blur" }
  ]
};

// 格式化日期
const formatDate = (date: string | Date | undefined) => {
  if (!date) return "--";
  const d = new Date(date);
  return d
    .toLocaleDateString("zh-CN", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit"
    })
    .replace(/\//g, "-");
};

// 处理人字段改为输入框，不再需要选项加载

// 加载派工数据
const loadWorkAssignmentData = async () => {
  loading.value = true;
  // 确保传递正确的分页参数，同时添加tenantId（如果需要的话）
  const queryDto: WorkAssignmentQueryDto = {
    page: currentPage.value,
    limit: pageSize.value,
    tenantId: undefined, // 添加租户ID，后端提示tenantId为null
    keyword: searchKeyword.value,
    // 不再单独搜索处理人，通过keyword统一搜索
    completionStatus: selectedCompletionStatus.value || undefined
  };

  try {
    console.log("发送的查询参数:", queryDto);
    const response = await getWorkAssignmentList(queryDto);
    if (response.code === 0 || response.code === 200) {
      workAssignments.value = response.data?.list || [];
      totalCount.value = response.data?.total || 0;
    } else {
      ElMessage.error(response.message || "获取派工数据失败");
    }
  } catch (error) {
    console.error("获取派工数据失败:", error);
    ElMessage.error("获取派工数据失败");
  } finally {
    loading.value = false;
  }
};

// 搜索方法
const handleSearch = () => {
  currentPage.value = 1;
  loadWorkAssignmentData();
};

// 重置搜索
const handleReset = () => {
  searchKeyword.value = "";
  selectedCompletionStatus.value = "";
  currentPage.value = 1;
  loadWorkAssignmentData();
};

// 分页变化
const handleSizeChange = (size: number) => {
  pageSize.value = size;
  currentPage.value = 1;
  loadWorkAssignmentData();
};

const handlePageChange = (current: number) => {
  currentPage.value = current;
  loadWorkAssignmentData();
};

// 添加派工
const handleAdd = () => {
  isDetail.value = false;
  dialogTitle.value = "新增派工信息";
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

// 编辑派工
const handleEdit = async (row: WorkAssignmentListVo) => {
  isDetail.value = false;
  dialogTitle.value = "编辑派工信息";
  resetForm();
  // 在resetForm后重新设置isEdit状态
  isEdit.value = true;

  try {
    // 先使用表格行数据进行快速回显，确保用户体验
    formData.id = row.id;
    formData.repairReportId = row.repairReportId;
    formData.assignmentTime = row.assignmentTime || "";
    formData.handler = row.handler || "";
    formData.totalFee = row.totalFee || 0;
    formData.serviceAddress = row.serviceAddress || "";
    formData.requiredTasks = row.requiredTasks || "";
    formData.assignmentNotes = row.assignmentNotes || "";
    formData.completionTime = row.completionTime || "";
    formData.completionStatus = row.completionStatus || "未完成";

    // 立即显示弹窗，不等待详情加载完成
    dialogVisible.value = true;

    // 同时异步请求最新数据以确保数据准确性
    try {
      const response = await getWorkAssignmentById(row.id!);
      if ((response.code === 0 || response.code === 200) && response.data) {
        const data = response.data;
        formData.id = data.id;
        formData.repairReportId = data.repairReportId;
        formData.assignmentTime = data.assignmentTime || "";
        formData.handler = data.handler || "";
        formData.totalFee = data.totalFee || 0;
        formData.serviceAddress = data.serviceAddress || "";
        formData.requiredTasks = data.requiredTasks || "";
        formData.assignmentNotes = data.assignmentNotes || "";
        formData.completionTime = data.completionTime || "";
        formData.completionStatus = data.completionStatus || "未完成";
      }
    } catch (detailError) {
      console.log("异步加载最新数据失败，但不影响编辑操作", detailError);
      // 静默失败，不影响用户体验
    }
  } catch (error) {
    console.error("编辑派工信息失败:", error);
    ElMessage.error("编辑派工信息失败");
  }
};

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  Object.assign(formData, {
    id: undefined,
    repairReportId: undefined,
    assignmentTime: "",
    handler: "",
    totalFee: 0,
    serviceAddress: "",
    requiredTasks: "",
    assignmentNotes: "",
    completionTime: "",
    completionStatus: "未完成"
  });
  isEdit.value = false;
  isDetail.value = false;
};

// 保存派工信息
const handleSave = async () => {
  if (!formRef.value) return;

  try {
    await formRef.value.validate();

    ElLoading.service({
      lock: true,
      text: "正在保存...",
      background: "rgba(0, 0, 0, 0.7)"
    });

    // 格式化所有日期字段为正确的字符串格式
    const formatDateField = (date: any) => {
      if (!date) return "";

      // 创建日期对象
      const dateObj =
        typeof date === "string" ? new Date(date) : new Date(date);

      // 检查日期是否有效
      if (isNaN(dateObj.getTime())) return "";

      // 格式化为后端可接受的日期时间格式: YYYY-MM-DD HH:mm:ss
      const year = dateObj.getFullYear();
      const month = String(dateObj.getMonth() + 1).padStart(2, "0");
      const day = String(dateObj.getDate()).padStart(2, "0");
      const hours = String(dateObj.getHours()).padStart(2, "0");
      const minutes = String(dateObj.getMinutes()).padStart(2, "0");
      const seconds = String(dateObj.getSeconds()).padStart(2, "0");

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    };

    const submitData = {
      ...formData,
      assignmentTime: formatDateField(formData.assignmentTime),
      completionTime: formatDateField(formData.completionTime)
    };

    let response;
    if (isEdit.value) {
      response = await updateWorkAssignment(
        submitData as WorkAssignmentUpdateDto
      );
    } else {
      response = await addWorkAssignment(submitData as WorkAssignmentAddDto);
    }

    if (response.code === 0 || response.code === 200) {
      ElMessage.success(isEdit.value ? "更新成功" : "添加成功");
      dialogVisible.value = false;
      await loadWorkAssignmentData();
    } else {
      ElMessage.error(
        response.message || (isEdit.value ? "更新失败" : "添加失败")
      );
    }
  } catch (error: any) {
    console.error("保存派工信息失败:", error);
    if (!error?.message?.includes("cancel")) {
      ElMessage.error("保存失败");
    }
  } finally {
    ElLoading.service().close();
  }
};

// 关闭对话框
const closeDialog = () => {
  dialogVisible.value = false;
  resetForm();
};

// 删除派工
const handleDelete = async (row: WorkAssignmentListVo) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除派工信息「${row.requiredTasks}」吗？`,
      "确认删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await deleteWorkAssignment(row.id!);
    if (response.code === 0 || response.code === 200) {
      ElMessage.success("删除成功");
      await loadWorkAssignmentData();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error: any) {
    if (!error?.message?.includes("cancel")) {
      console.error("删除派工信息失败:", error);
    }
  }
};

// 查看详情
const handleDetail = async (row: WorkAssignmentListVo) => {
  isDetail.value = true;
  dialogTitle.value = "派工信息详情";
  resetForm();
  // 在resetForm后重新设置isDetail状态
  isDetail.value = true;

  // 使用表格行数据进行快速回显
  formData.id = row.id;
  formData.repairReportId = row.repairReportId;
  formData.assignmentTime = row.assignmentTime || "";
  formData.handler = row.handler || "";
  formData.totalFee = row.totalFee || 0;
  formData.serviceAddress = row.serviceAddress || "";
  formData.requiredTasks = row.requiredTasks || "";
  formData.assignmentNotes = row.assignmentNotes || "";
  formData.completionTime = row.completionTime || "";
  formData.completionStatus = row.completionStatus || "未完成";

  // 显示弹窗
  dialogVisible.value = true;
};

// 打开回单弹窗
const handleFeedback = async (row: WorkAssignmentListVo) => {
  currentRepair.value = row;
  receiptForm.repairReportId = row.repairReportId || 0;
  receiptForm.handlingSituation = "已完成";
  receiptForm.remarks = "";
  receiptDialogVisible.value = true;
};

// 提交回单
const submitFeedback = async () => {
  if (!receiptFormRef.value) return;

  try {
    await receiptFormRef.value.validate();

    ElLoading.service({
      lock: true,
      text: "正在提交回单...",
      background: "rgba(0, 0, 0, 0.7)"
    });

    const submitData: WorkAssignmentReceiptDto = {
      repairReportId: receiptForm.repairReportId,
      handlingSituation: receiptForm.handlingSituation,
      remarks: receiptForm.remarks || ""
    };

    const response = await submitReceipt(submitData);

    if (response.code === 0 || response.code === 200) {
      ElMessage.success("回单成功");

      // 如果处理情况是已完成并待收款，提示账单生成和缴费信息
      if (receiptForm.handlingSituation === "已完成并待收款") {
        ElMessage.warning("账单已生成，请及时缴费");
      }

      receiptDialogVisible.value = false;
      await loadWorkAssignmentData();
    } else {
      ElMessage.error(response.message || "回单失败");
    }
  } catch (error: any) {
    console.error("提交回单失败:", error);
    if (!error?.message?.includes("cancel")) {
      ElMessage.error("回单失败，请稍后重试");
    }
  } finally {
    ElLoading.service().close();
  }
};

// 关闭回单弹窗
const closeReceiptDialog = () => {
  receiptDialogVisible.value = false;
  if (receiptFormRef.value) {
    receiptFormRef.value.resetFields();
  }
};

// 状态标签样式
const getStatusTagType = (status: string) => {
  switch (status) {
    case "未完成":
      return "danger";
    case "已完成":
      return "success";
    case "进行中":
      return "primary";
    default:
      return "info";
  }
};

// 组件挂载时加载数据
onMounted(async () => {
  await loadWorkAssignmentData();
});
</script>

<template>
  <div class="work-assignment-container">
    <div class="header-bar">
      <div class="search-box">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入处理人/服务地址/要求处理事项搜索"
          style="width: 300px; margin-right: 10px"
          @keyup.enter="handleSearch"
        >
          <template #append>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </template>
        </el-input>

        <el-select
          v-model="selectedCompletionStatus"
          placeholder="完成情况"
          style="width: 180px; margin-right: 10px"
          clearable
        >
          <el-option
            v-for="item in completionStatusOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
    </div>

    <div class="table-container">
      <el-table
        v-loading="loading"
        :data="workAssignments"
        style="width: 100%"
        border
      >
        <el-table-column label="派发时间" min-width="120">
          <template #default="{ row }">
            {{ formatDate(row.assignmentTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="handler" label="处理人" min-width="100" />
        <el-table-column label="计费总额(元)" min-width="120">
          <template #default="{ row }">
            {{ row.totalFee || 0 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="serviceAddress"
          label="服务地址"
          min-width="180"
        />
        <el-table-column
          prop="requiredTasks"
          label="要求处理事项"
          min-width="200"
          show-overflow-tooltip
        />
        <el-table-column
          prop="assignmentNotes"
          label="派工备注"
          min-width="150"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            {{ row.assignmentNotes || "--" }}
          </template>
        </el-table-column>
        <el-table-column label="完成时间" min-width="120">
          <template #default="{ row }">
            {{ formatDate(row.completionTime) }}
          </template>
        </el-table-column>
        <el-table-column
          prop="completionStatus"
          label="完成情况"
          min-width="100"
        >
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.completionStatus)">{{
              row.completionStatus || "未完成"
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="200" fixed="right">
          <template #default="{ row }">
            <el-button
              v-if="row.completionStatus !== '已完成'"
              type="success"
              link
              size="small"
              @click="handleFeedback(row)"
            >
              回单
            </el-button>
            <el-button type="info" link size="small" @click="handleDetail(row)">
              查看
            </el-button>
            <el-button
              type="warning"
              link
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              link
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="prev, pager, next, jumper, sizes, total"
          :total="totalCount"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </div>

    <!-- 派工信息对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="700px"
      :before-close="closeDialog"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        :disabled="isDetail"
        label-width="120px"
        class="work-assignment-form"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="派发时间" prop="assignmentTime">
              <el-date-picker
                v-model="formData.assignmentTime"
                type="datetime"
                placeholder="请选择派发时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="处理人" prop="handler">
              <el-input v-model="formData.handler" placeholder="请输入处理人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计费总额(元)" prop="totalFee">
              <el-input
                v-model.number="formData.totalFee"
                placeholder="请输入计费总额"
                type="number"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="服务地址" prop="serviceAddress">
              <el-input
                v-model="formData.serviceAddress"
                placeholder="请输入服务地址"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="要求处理事项" prop="requiredTasks">
              <el-input
                v-model="formData.requiredTasks"
                type="textarea"
                :rows="3"
                placeholder="请输入要求处理事项"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="派工备注" prop="assignmentNotes">
              <el-input
                v-model="formData.assignmentNotes"
                type="textarea"
                :rows="3"
                placeholder="请输入派工备注"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成时间" prop="completionTime">
              <el-date-picker
                v-model="formData.completionTime"
                type="datetime"
                placeholder="请选择完成时间"
                style="width: 100%"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="完成情况" prop="completionStatus">
              <el-select
                v-model="formData.completionStatus"
                placeholder="请选择完成情况"
              >
                <el-option
                  v-for="item in completionStatusOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button v-if="!isDetail" type="primary" @click="handleSave"
            >确定</el-button
          >
        </span>
      </template>
    </el-dialog>

    <!-- 回单弹窗 -->
    <el-dialog
      v-model="receiptDialogVisible"
      title="派工回单"
      width="600px"
      :before-close="closeReceiptDialog"
    >
      <div v-if="currentRepair">
        <div class="receipt-info">
          <h3>回单</h3>
          <div class="receipt-section">
            <div class="receipt-row">
              <span class="receipt-label">地址：</span>
              <span>{{ currentRepair.serviceAddress || "-" }}</span>
            </div>
            <div class="receipt-row">
              <span class="receipt-label">申请人工单ID：</span>
              <span>{{ currentRepair.repairReportId || "-" }}</span>
            </div>
            <div class="receipt-row">
              <span class="receipt-label">处理人：</span>
              <span>{{ currentRepair.handler || "-" }}</span>
            </div>
            <div class="receipt-row">
              <span class="receipt-label">派发时间：</span>
              <span>{{
                currentRepair.assignmentTime
                  ? formatDate(currentRepair.assignmentTime)
                  : "-"
              }}</span>
            </div>
            <div class="receipt-row">
              <span class="receipt-label">详细情况：</span>
              <span>{{ currentRepair.requiredTasks || "-" }}</span>
            </div>
          </div>
        </div>

        <div class="receipt-form-section">
          <h4>回单信息</h4>
          <el-form
            ref="receiptFormRef"
            :model="receiptForm"
            :rules="receiptRules"
            label-width="100px"
          >
            <el-form-item label="处理情况*" prop="handlingSituation">
              <el-select
                v-model="receiptForm.handlingSituation"
                placeholder="请选择处理情况"
                style="width: 100%"
              >
                <el-option
                  v-for="item in handlingSituationOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remarks">
              <el-input
                v-model="receiptForm.remarks"
                type="textarea"
                placeholder="请输入备注"
                :rows="4"
                style="width: 100%"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>

      <template #footer>
        <el-button @click="closeReceiptDialog">取消</el-button>
        <el-button type="primary" @click="submitFeedback">提交</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
.receipt-info {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.receipt-section {
  margin-top: 15px;
}

.receipt-row {
  margin-bottom: 10px;
  font-size: 14px;
}

.receipt-label {
  font-weight: bold;
  margin-right: 10px;
  display: inline-block;
  width: 100px;
  text-align: right;
}

.receipt-form-section {
  margin-top: 20px;
}

.receipt-form-section h4 {
  margin-bottom: 15px;
  font-size: 16px;
  font-weight: bold;
}
</style>

<style scoped>
.work-assignment-container {
  padding: 20px;
}

.header-bar {
  margin-bottom: 20px;
}

.search-box {
  display: flex;
  align-items: center;
}

.table-container {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.work-assignment-form {
  max-height: 60vh;
  overflow-y: auto;
}
</style>
